package cn.summit.passwordsty.rsa;

import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;

/**
 * @author summit
 * @since 2021/8/15 15:01
 */
public class SignaturedDataTest {

	public static void main(String[] args) throws Exception {

		String input = "sss";
		PublicKey publicKey = RSATest.getPublicKey("a.pub", "RSA");
		PrivateKey privateKey = RSATest.getPrivateKey("a.pri", "RSA");
		String algorithm = "sha256withrsa";
		String signatureData = getSignature(input, algorithm, privateKey);

		Boolean aBoolean = verifySignature(input, algorithm, publicKey, signatureData);
		System.out.println("数字验证结果：" + aBoolean);
	}

	public static String getSignature(String input, String algorithm, PrivateKey key) throws Exception {
		Signature signature = Signature.getInstance(algorithm);
		signature.initSign(key);

		signature.update(input.getBytes(StandardCharsets.UTF_8));

		byte[] sign = signature.sign();

		return Base64.getEncoder().encodeToString(sign);
	}

	public static Boolean verifySignature(String input, String algorithm, PublicKey key, String signatureData) throws Exception {
		Signature signature = Signature.getInstance(algorithm);
		signature.initVerify(key);

		signature.update(input.getBytes(StandardCharsets.UTF_8));

		return signature.verify(Base64.getDecoder().decode(signatureData));
	}
}
